package com.ldfile.server.utils;

import com.google.zxing.WriterException;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;
import com.ldfile.server.dto.PdfQrcodeDTO;
import lombok.Getter;
import lombok.Setter;
import org.springframework.util.CollectionUtils;
import org.springframework.util.FileCopyUtils;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 生成PDF文件信息
 */
public class PdfUtil {

    static BaseFont base;


    static Map<String, PageAttr> pageAttrMap;

    static {
        //加载背景图片
        try {
            base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            pageAttrMap = new HashMap<>();
            //样式1:A4大小,肉禽追溯
            pageAttrMap.put("1", new PageAttr(15, 163, 310, 200, 560,
                    270, PageSize.A4, "https://www.anning.city/file-server/zyczs/bgimg.jpg"));
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Getter
    @Setter
    static class PageAttr {
        int fontSize;
        int imgx;
        int imgy;
        int titlex;
        int titley;
        int qrcodeWitch;
        Rectangle pageSize;
        byte[] bgImage;

        public PageAttr(int fontSize, int imgx, int imgy, int titlex, int titley, int qrcodeWitch, Rectangle pageSize, String bgiUrl) throws IOException {
            this.fontSize = fontSize;
            this.imgx = imgx;
            this.imgy = imgy;
            this.titlex = titlex;
            this.titley = titley;
            this.qrcodeWitch = qrcodeWitch;
            this.pageSize = pageSize;
            bgImage = FileCopyUtils.copyToByteArray(loadImgfromUrl(bgiUrl));
        }
    }


    public static void createPdf(List<PdfQrcodeDTO> list, OutputStream os) throws DocumentException, IOException, WriterException {
        Document document = new Document();
        PdfWriter.getInstance(document, os);
        document.open();
        if (!CollectionUtils.isEmpty(list)) {
            for (PdfQrcodeDTO pdfQrcodeDTO : list) {
                createPage(pdfQrcodeDTO, document);
            }
        }
        document.close();
    }

    public static void createPage(PdfQrcodeDTO pdfQrcodeDTO, Document document) throws DocumentException, IOException, WriterException {
        PageAttr pageAttr = pageAttrMap.get(pdfQrcodeDTO.getStyle());
        if (pageAttr == null) {
            pageAttr = pageAttrMap.get("1");
        }
        document.setMargins(0, 0, pageAttr.titley, 0);
        document.setPageSize(pageAttr.pageSize);
        document.newPage();
        Image tImgCover = Image.getInstance(pageAttr.bgImage);
        /* 设置图片的位置 */
        tImgCover.setAbsolutePosition(0, 0);
        /* 设置图片的大小 */
        tImgCover.scaleAbsolute(pageAttr.pageSize.getWidth(), pageAttr.pageSize.getHeight());
        document.add(tImgCover);
        createContent(pdfQrcodeDTO.getTitle(), pdfQrcodeDTO.getContent(), pdfQrcodeDTO.getLogo(), pageAttr, document);
    }

    public static void createContent(String title, String content, String logo, PageAttr pageAttr, Document document) throws DocumentException,
            IOException, WriterException {
        Paragraph p = new Paragraph();
        p.setFont(new Font(base, pageAttr.getFontSize()));
        p.setAlignment(Element.ALIGN_CENTER);
        p.add(title);
        InputStream inputStream = loadImgfromUrl(logo);
        BufferedImage jpg = QRCodeUtil.zxingCodeCreate(content, null, pageAttr.getQrcodeWitch(), pageAttr.getQrcodeWitch(), "jpg", 3, inputStream);
        Image instance = Image.getInstance(jpg, null, false);
        instance.setAlignment(Element.ALIGN_CENTER);
        instance.setAbsolutePosition(pageAttr.imgx, pageAttr.imgy);
        document.add(instance);
        document.add(p);
    }

    /**
     * 加载网络资源
     *
     * @param url
     * @return
     * @throws IOException
     */
    static InputStream loadImgfromUrl(String url) throws IOException {
        URL imgUrl = new URL(url); // 创建URL
        URLConnection urlConnection = imgUrl.openConnection();
        urlConnection.connect();
        HttpURLConnection httpconn = (HttpURLConnection) urlConnection;
        int responseCode = httpconn.getResponseCode();
        if (responseCode == 200) {
            return httpconn.getInputStream();
        }
        return null;
    }


}
